package leetcode;

import java.util.Stack;

public class Code32 {
    public static void main(String[] args) {
        System.out.println(new Code32().longestValidParentheses("()()(())"));
    }

    public int longestValidParentheses(String s) {
        char[] chars = s.toCharArray();
        int[] index = new int[chars.length];
        Stack<Character> stack = new Stack<>();
        int max = 0;
        for (int a = 0; a < chars.length; a++) {
            if (chars[a] == '(') {
                stack.push(chars[a]);
                index[a] = 0;
                max = Integer.max(max, index[a]);
            } else {
                if (stack.empty()) {
                    index[a] = 0;
                    continue;
                }
                stack.pop();
                index[a] = index[a - 1] + 1;
                if (a - index[a] * 2 > 0) {
                    index[a] += index[a - index[a] * 2];
                }
                max = Integer.max(max, index[a]);
            }
        }
        return max * 2;
    }
}
